from flask import Flask, render_template, request, flash, redirect, url_for, session, send_from_directory
from forms import LoginForm, PrimeForm, UploadForm, MultiUploadForm
from flask_wtf.csrf import validate_csrf
from wtforms import ValidationError

import os
import uuid

app = Flask(__name__)

app.secret_key = 'a key'
# 限制请求报文大小
app.config['MAX_CONTENT_LENGTH'] = 3*1024*1024
app.config['UPLOAD_PATH'] = os.path.join(app.root_path, 'uploads')
app.config['ALLOWED_EXTENSIONS'] = ['png', 'jpg', 'jpeg', 'gif']


@app.route('/')
def index():
    return render_template('forms/index.html')

# 默认只响应GET
@app.route('/basic', methods=['get', 'post'])
def basic():
    form = LoginForm()  # GET + POST
    # request.method == 'POST' and form.validate() 等价于 form.validate_on_submit()
    if form.validate_on_submit():
        username = form.username.data
        flash('Welcome to %s!!!' % username)
        return redirect(url_for('index'))
    return render_template('forms/bootstrap.html', form=form)


# 验证器
@app.route('/prime', methods=['get', 'post'])
def prime():
    form = PrimeForm()
    if form.validate_on_submit():
        number = form.number.data
        if int(number) % 2 == 0:
            result = '偶数'
        else:
            result = '奇数'
        return render_template('forms/prime.html', form=form, result=result)
    return render_template('forms/prime.html', form=form)


# 单个文件上传视图函数
@app.route('/upload', methods=['get', 'post'])
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        print('---> pass valid...')
        f = form.photo.data
        filename = random_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        flash('上传成功!')
        session['filenames'] = [filename]
        return redirect(url_for('show_images'))
    return render_template('forms/upload.html', form=form)


# 多个文件上传的视图函数
@app.route('/multi-upload', methods=['get', 'post'])
def multi_upload():
    form = MultiUploadForm()
    if request.method == 'POST':
        filenames = []
        # 验证CSRF
        try:
            validate_csrf(form.csrf_token.data)
        except ValidationError:
            flash('CRSF token Error.')

        # 检查文件是否存在
        if 'photo' not in request.files:
            flash('需要填写该字段.')
            return redirect(url_for('multi_upload'))
        
        print(form.photo.data)

        for f in request.files.getlist('photo'):
            # 检查文件类型
            if f and allowed_file(f.filename):
                filename = random_filename(f.filename)
                f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
                filenames.append(filename)
            else:
                flash('错误的文件类型.')
                return redirect(url_for('multi_upload'))

        flash('上传成功')
        session['filenames'] = filenames
        return redirect(url_for('show_images'))
    return render_template('forms/upload.html', form=form)


@app.route('/uploaded-images')
def show_images():
    return render_template('forms/uploaded.html')


@app.route('/uploads/<path:filename>')
def get_file(filename):
    return send_from_directory(app.config['UPLOAD_PATH'], filename)


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']


def random_filename(filename):
    ext = os.path.splitext(filename)[1]
    new_filename = uuid.uuid4().hex + ext
    return new_filename
